package edu.mju.msmservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import edu.mju.msmservice.service.MsmService;
import edu.mju.msmservice.util.ConstPropertiesUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @Author: wyp
 * @Date: 2020/9/27 9:48
 */
@Service
public class MsmServiceImpl implements MsmService {

    /**
     * 发送短信的方法
     * @param param map存随机验证码
     * @param phone 手机号
     * @return 发送成功：true 失败：false
     */
    @Override
    public boolean sendMsm(Map<String, Object> param, String phone) {
        //如果手机号为空，返回false
        if(StringUtils.isEmpty(phone)){
            return false;
        }
        //getProfile("地域节点","id","密钥")
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", ConstPropertiesUtil.ACCESS_KEY_ID,ConstPropertiesUtil.ACCESS_KEY_SECRET);
        IAcsClient client = new DefaultAcsClient(profile);

        //设置固定参数
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");

        //设置发送参数
        request.putQueryParameter("PhoneNumbers",phone);
        request.putQueryParameter("SignName","闽院个人在线教育视频平台");
        request.putQueryParameter("TemplateCode",ConstPropertiesUtil.ACCESS_TEMPALTE_CODE);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));

        //最终发送
        try {
            CommonResponse commonResponse = client.getCommonResponse(request);
            //获取发送是否成功的消息
            return commonResponse.getHttpResponse().isSuccess();
        } catch (ClientException e) {
            e.printStackTrace();
            return false;
        }

    }
}
